#pragma once

#include <iostream>

namespace solution_019
{

struct ListNode
{
    int val;
    ListNode* next;
    ListNode() : val(0), next(nullptr) { }
    ListNode(int x) : val(x), next(nullptr) { }
    ListNode(int x, ListNode* next) : val(x), next(next) { }

    void print()
    {
        ListNode* list = this;
        std::cout << list->val;
        while (list->next) {
            std::cout << "-->" << list->next->val;
            list = list->next;
        }
        std::cout << "\n";
    }
};


class Solution
{
public:
    ListNode* removeNthFromEnd(ListNode* head, int n)
    {
        ListNode root(0, head);
        auto prev = &root;
        auto node = &root;
        while (n > 0) {
            node = node->next;
            --n;
        }
        while (node->next) {
            prev = prev->next;
            node = node->next;
        }
        node = prev->next;
        prev->next = node->next;
        delete node;
        return root.next;
    }
};

}  /* namespace solution_019 */
